<?php

namespace app\admin\controller\stock;

use app\common\controller\Backend;
use app\common\model\goods\Goods;
use app\common\model\stock\LossGoods;
use app\common\model\goods\GoodsHouseStock;
use think\Db;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Stock extends Backend
{
    
    /**
     * Loss模型对象
     * @var \app\common\model\stock\Stock
     */
    protected $model = null;
    protected $thisurl = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\stock\Stock;

        $this->thisurl = handlePrefix().'://'.$_SERVER['SERVER_NAME'];
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['storehouse'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','createtime','number','explain','operator','company','status']);
                $row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
            }
            $list = collection($list)->toArray();

            $statuss = $this->model->loss_status();
            foreach ($list as &$v){
                $v['ystatus'] = $v['status'];
                $v['status'] = $statuss[$v['status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add(){
        if ($this->request->isAjax())
        {
            $storehouse_id = input('storehouse_id/d',0);
            $srow = Db::name('storehouse')->where(array('id'=>$storehouse_id))->find();
            if(empty($srow)){
                $this->error('仓库选择错误');
            }
            $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
            $num = $this->model->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $data = array(
                'number'=>'PK-'.date('Y-m-d').'-'.getnumber($num),
                'storehouse_id'=>$storehouse_id,
                'createtime'=>time(),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'explain'=>input('explain'),
            );
            $res = Db::name('stock_report')->insert($data);
            if($res){
                $this->success('添加报表成功');
            }else{
                $this->error('添加报表失败');
            }

        }
        return $this->view->fetch();
    }
    public function detail($ids = null){
        $row = $this->model->find($ids);
        if($this->request->isAjax()){
            $page = input('offset/d');
            $pagesize = input('limit/d');
            $where = [];
            $filter = json_decode(input('filter'),true);

            $search = input('search');
            if(!empty($search)){
                $where['title|specs'] = array('like','%'.$search.'%');
            }
            $storehouse_id = $filter['storehouse_id'];
            if(empty($storehouse_id)){
                $this->error('仓库异常');
            }
            $where['storehouse_id'] = $storehouse_id;
            if(!empty($filter)){
                foreach ($filter as $k => $v){
                    if($k == 'is_stock'){
                        $rgids = Db::name('stock_report_goods')->where(['report_id'=>$ids])->column('goods_id');
                        $where['goods_id'] =array('notin',$rgids);
                    }
                }
            }
            $list = Db::name('goods')
                ->alias('g')
                ->where($where)
                ->join('goods_house_stock s','g.id = s.goods_id')
                ->limit($page,$pagesize)
                ->select();
            $total = Db::name('goods')
                ->alias('g')
                ->where($where)
                ->join('goods_house_stock s','g.id = s.goods_id')
                ->count();

            $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();

            $numbers = [];
            $gids = [];
            foreach ($list as &$v){
                $gids[] = $v['goods_id'];
                $numbers[] = $v['number'];
            }
            $prices = $this->getprice(implode(',',$numbers),$hrow['code']);
            $goodslist = Db::name('stock_report_goods')->where(['report_id'=>$ids,'goods_id'=>array('in',$gids)])->select();
            foreach ($list as &$v){
                $v['now_stock'] = 0;
                $v['old_stock'] = 0;
//                $v['image'] = $this->thisurl.'/assets/web/images/zanwu.png';
                foreach ($goodslist as $value){
                    if($v['goods_id'] == $value['goods_id']){
                        $v['now_stock'] = $value['stock'];
                        $v['old_stock'] = $value['old_stock'];
                    }
                }
            }
            return json(
                [
                    'rows'=>$list,
                    'total'=>$total,
                ]
            );
            exit;
        }

        $this->assign('house_id',$row['storehouse_id']);
        $this->assign('report_id',$ids);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    protected function getprice($numbers,$code){
        $url =  config('site.syncurl').'/api/sync/batchprice';
        $json = curl_post($url,array(
            'numbers'=>$numbers,
            'code'=>$code,
            'appkey'=>config('site.appkey'),
        ));
        $json = json_decode($json,true);
        if($json['code'] == 9){
            return [];
        }
        if(!empty($json) && $json['code']  == 1){
            return $json['data'];
        }else{
            return [];
        }
    }
    public function addstock(){
        return $this->model->addstocks();
    }
    public function end(){
        $report_id = input('report_id/d',0);
        $res = $this->model->save(array('status'=>2),array('id'=>$report_id));
        if($res){
            $this->success('结束盘点');
        }
        $this->error('异常');
        $this->success('');
    }
}
